package main.动态规划;

/**
 * @author tmh
 * @date 2024/9/23 16:27
 * @description
 */
public class T72编辑距离 {
    public int minDistance(String word1, String word2) {
        //dp[i][j]表示把i-1为结尾的字符串编辑成j-1为结尾的字符串的最小编辑次数
        int m = word1.length();
        int n = word2.length();
        int[][] dp = new int[m + 1][n + 1];
        //初始化第一行
        for (int i = 0; i <= n; i++) {
            dp[0][i] = i;
        }
        //初始化第一列
        for (int j = 0; j <= m; j++) {
            dp[j][0] = j;
        }
        for (int i = 1; i <= m; i++) {
            for (int j = 1; j <= n; j++) {
                if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                    //如果相同
                    dp[i][j] = dp[i - 1][j - 1];
                }else {
                    //如果不同,就在上一次的基础上+1
                    //word1删除字符，或者word2删除字符，或者替换。三种情况
                    dp[i][j]=Math.min(Math.min(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1])+1;
                }
            }
        }
        return dp[m][n];
    }
}
